package cn.tedu.crm.orders.controller;

import cn.hutool.core.util.StrUtil;
import cn.tedu.crm.base.exception.ServiceException;
import cn.tedu.crm.base.response.JsonResult;
import cn.tedu.crm.orders.pojo.vo.OrdersImgVO;
import cn.tedu.crm.orders.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/crm/img")
public class ImgController {

    @Value("${app.upload.path}")
    private String uploadPath;

    @Value("${app.upload.url-prefix}")
    private String urlPrefix;
    @Autowired
    private OrdersService ordersService;

    private static final Map<String, String> CONTENT_TYPE_MAPPING = new HashMap<>();

    static {
        CONTENT_TYPE_MAPPING.put(".jpg", "image/jpg");
        CONTENT_TYPE_MAPPING.put(".jpeg", "image/jpg");
        CONTENT_TYPE_MAPPING.put(".png", "image/jpg");
        CONTENT_TYPE_MAPPING.put(".gif", "image/gif");
        CONTENT_TYPE_MAPPING.put(".bmp", "image/bmp");
    }

    @PostMapping("/upload/{type}/{id}")
    public JsonResult uploadImage(@RequestPart("file") MultipartFile multipartFile,
                                  @PathVariable("type") String type,
                                  @PathVariable("id") Long id) {
        return getImgUrl(multipartFile, type, id);
    }
    @PostMapping("/uploadR/{id}")
    public JsonResult uploadImageRe(@RequestPart("file") MultipartFile multipartFile,
                                  @PathVariable("id") Long id) {
        return getImgUrl(multipartFile, null, id);
    }

    private JsonResult<?> getImgUrl(MultipartFile multipartFile, String type, Long id) {
        // 获取原文件名
        log.debug("上传图片-入参文件:{},文件类型:{},订单Id:{}", multipartFile, type, id);
        String originalFilename = multipartFile.getOriginalFilename();

        // 获取文件后缀
        int lastIndex;
        if (originalFilename == null || (lastIndex = originalFilename.lastIndexOf(".")) == -1) {
            throw new ServiceException("图片格式不支持");
        }
        String ext = originalFilename.substring(lastIndex).toLowerCase();

        // 获取内容类型
        String contentType = CONTENT_TYPE_MAPPING.get(ext);
        if (contentType == null) {
            throw new ServiceException("图片格式不支持");
        }

        // 生成新的文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + ext;

        // 生成存储文件夹
        String folder = DateTimeFormatter.ofPattern("/yyyy/MM/dd/").format(LocalDateTime.now());
        File targetDir = new File(uploadPath, folder);
        if (!targetDir.exists()) targetDir.mkdirs();

        try {
            multipartFile.transferTo(new File(targetDir, fileName));
        } catch (IOException e) {
            log.error("上传图片异常: {}", e.getMessage());
            return JsonResult.error("上传图片失败，请稍后再试");
        }
        if (type != null){
            ordersService.imgAdd(folder + fileName, id, type);
        }else {
            ordersService.refundAdd(folder + fileName, id);
        }
        // 拼接完整的url地址，返回
        return JsonResult.success(urlPrefix + folder + fileName);
    }

    @PostMapping("/remove")
    public JsonResult remove(String url) {
        if (StrUtil.isEmpty(url)) {
            return JsonResult.error("url不能为空");
        }
        if (url.startsWith(urlPrefix)) {
            url = url.substring(urlPrefix.length());
        }
        new File(uploadPath + url).delete();
        return JsonResult.success(null);
    }

    @PostMapping("/get/img/{id}")
    public JsonResult getImg(@PathVariable Long id){
        log.debug("获取图片-入参订单ID:{}",id);
        Map<String,List<OrdersImgVO>>  map = ordersService.loadImg(id);
        return JsonResult.ok(map);
    }


    @PostMapping("/imgDel")
    public JsonResult imgDel(@RequestBody Map<String, List<OrdersImgVO>> mapImg){
        log.debug("订单图纸删除:{}",mapImg);
        ordersService.imgDel(mapImg);
        return JsonResult.ok();
    }

}
